<?php

namespace mdm\admin\models\form;

use Yii;
use mdm\admin\models\User;
use yii\base\Model;

/**
 * Description of ChangePassword
 *
 * @author Misbahul D Munir <misbahuldmunir@gmail.com>
 * @since 1.0
 */
class ChangeRealname extends Model
{
    public $realname;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['realname', 'string', 'min' => 2, 'max' => 255],
            ['realname', 'filter', 'filter' => 'trim'],
            ['realname', 'required', 'message' => '真实姓名必须为2-5个汉字'],
            ['realname', 'match', 'pattern' => '/^[\x{4e00}-\x{9fa5}]{2,5}$/u', 'message' => '真实姓名必须为2-5个汉字'],
        ];
    }

    /**
     * Change realname.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function change()
    {
        if ($this->validate()) {
            /* @var $user User */
            $user = Yii::$app->user->identity;
            $user->realname = $this->realname;
            if ($user->save()) {
                return true;
            }
        }

        return false;
    }
}
